package tech.aistar.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.aistar.mapper.UserMapper;
import tech.aistar.pojo.Card;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;
import tech.aistar.service.CardService;
import javax.servlet.http.HttpServletRequest;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private CardService cardService;

    /**
     * 登录逻辑
     * @param username 用户名
     * @param password 密码
     * @param request 请求对象
     * @return
     */
    @Override
    public Result login(String username, String password, HttpServletRequest request) {

        if (StrUtil.hasBlank(username, password)) {
            return new Result("400", "参数不全", null);
        }
        // 查询用户
        User user = getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username).eq(User::getPassword, password));
        if (user == null) {
            return new Result("400", "用户不存在", null);
        }
        request.getSession().setAttribute("userSession", user);
        return new Result("200", "成功", null);
    }

    /**
     * 更新密码
     * @param password 密码
     * @param newPassword 新密码
     * @param confirmPassword 确认密码
     *
     * @return
     */
    @Override
    public Result updatePassword(String password, String confirmPassword, String newPassword, User user) {

        if (StrUtil.hasBlank( password, confirmPassword,newPassword)) {
            return new Result("400", "参数不全", null);
        }
        if (!newPassword.equals(confirmPassword)) {
            return new Result("400", "密码不一致", null);
        }
        user.setPassword(newPassword);
        updateById(user);
        return new Result("200", "成功", null);
    }


    /**
     * 注册逻辑
     * @param username 用户名
     * @param password 密码
     * @param email 邮箱
     * @param name 姓名
     * @return
     */
    @Override
    public Result register(String username, String password, String email, String name) {

        User user = new User();
        user.setPassword(password);
        user.setName(name);
        user.setEmail(email);
        user.setUsername(username);

        User one = getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if (one != null) {
            return new Result("400", "用户已存在", null);
        }
        // 注册用户
        save(user);

        Card card = new Card();
        card.setUserId(user.getId());
        cardService.save(card);

        return new Result("200", "成功", null);
    }
}
